package com.jmz.apt.api.controller;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmz.apt.api.Helper.RequestHelper;
import com.jmz.apt.api.Helper.ResponseHelper;
import com.jmz.apt.api.Utils.MD5Util;
import com.jmz.apt.api.Utils.ObjectUtil;


import com.jmz.apt.api.Utils.TokenUtil;
import com.jmz.apt.api.common.AptConstant;
import com.jmz.apt.api.common.SecurityContextHolder;
import com.jmz.apt.api.dao.AdminRoleDao;
import com.jmz.apt.api.dto.impl.AdminTokenDto;
import com.jmz.apt.api.dto.impl.AdminUserDto;

import com.jmz.apt.api.entity.dbEntity.JmzAdminRole;
import com.jmz.apt.api.entity.dbEntity.JmzAdminUser;
import com.jmz.apt.api.entity.dbEntity.JmzAdminUserRoles;
import com.jmz.apt.api.enums.ResponseCode;
import com.jmz.apt.api.exception.BusinessException;
import com.jmz.apt.api.message.request.Condition;
import com.jmz.apt.api.message.request.RequestMessage;
import com.jmz.apt.api.message.request.RequestMessageTemplate;
import com.jmz.apt.api.message.response.ResponseMessage;
import com.jmz.apt.api.message.response.ResponseMessageTemplate;
import com.jmz.apt.api.service.AdminUserService;

import com.jmz.apt.api.service.LoginService;
import com.sun.deploy.net.HttpResponse;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.ContentHandler;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Created by fanglexue on 2019/10/23.
 */

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    ResponseMessageTemplate responseMessageTemplate;


    @Autowired
    LoginService loginService;

    @Autowired
    AdminRoleDao adminRoleDao;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    RequestHelper requestHelper;

    @RequestMapping(value="/adminList",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getAdmins(@RequestBody RequestMessage requestMessage){
        List<JmzAdminUser> adminUsers = adminUserService.getAdminUserList(requestMessage);

        //Entities are converted to DTOs
        ModelMapper modelMapper = new ModelMapper();
        List<AdminUserDto> userDTOS = modelMapper.map(adminUsers,new TypeToken<List<AdminUserDto>>(){}.getType());

        //Set response data
        ResponseHelper responseHelper = new ResponseHelper();
        responseHelper.setResponseDataSet("adminList",userDTOS);
        Integer pageNo = requestMessage.getMessage().getBody().getQuery().getPageno();
        Integer pageSize = requestMessage.getMessage().getBody().getQuery().getPagesize();
        Integer recountCount = userDTOS.size();
        Integer pageCount = (int)Math.ceil(adminUserService.count(requestMessage) / pageSize);
        responseHelper.setResponseQuery(pageNo,pageSize,recountCount,pageCount);
        responseHelper.setResponseBCode(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc());
        ResponseMessage responseResult = responseHelper.getResponseMessageTemplate().getResponseMessage();
        return  responseResult;
    }


    /**
     * @Description This method is used change  role of the administrator.
     * @Author { fanglexue on 2019/11/7 at 11:06 AM }
     * @Path /admin/convertRole
     */
    @RequestMapping(value="/convertRole",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage convertRole(@RequestBody RequestMessage requestMessage, ServletResponse response,
                                       ServletRequest request) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String token = httpServletRequest.getHeader("token");
        ResponseHelper responseHelper = new ResponseHelper();
        AdminTokenDto adminTokenDto = SecurityContextHolder.getAgent();
        Integer roleId = adminTokenDto.getRoleId();
        Integer adminId = adminTokenDto.getAdminId();
        RequestMessageTemplate requestMT = new RequestMessageTemplate(requestMessage);
        System.out.println(roleId);
        Condition cond = requestMT.getConditionByKey("roleId");
        Integer reqRoleId = Integer.valueOf(cond.getValue());
        if(!reqRoleId.equals(roleId)){
            /**
             * if the request role id not equals current role id of the administrator,
             *  then we check if it is legal.
             */
            JmzAdminUser jmzAdminUser = adminUserService.getAdminInfo(adminId);
            List<JmzAdminRole> adminRoles = jmzAdminUser.getAdminRoles();
            boolean isLegal = false;
            for(JmzAdminRole adminRole : adminRoles){
                if(adminRole.getId().equals(reqRoleId)){
                    isLegal = true;
                }
            }
            if(isLegal){
                loginService.clearRedisKey(token,adminTokenDto);
                adminTokenDto.setRoleId(reqRoleId);
                SecurityContextHolder.remove();
                SecurityContextHolder.addAgent(adminTokenDto);
                //System.out.println(adminTokenDto.getRoleId());
                String newToken = TokenUtil.conferToken(adminTokenDto, AptConstant.TOKEN_EXPIRE);
                httpServletResponse.setHeader("Cache-Control", "no-store");
                httpServletResponse.setHeader("token", newToken);
                responseHelper.setResponseBCode(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc());
                loginService.setTokenRedisMap(newToken,adminTokenDto);
                loginService.setTokenRedis(newToken);
                loginService.setAdminPermissions(adminTokenDto.getRoleId());
            }else{
                responseHelper.setResponseBCode(ResponseCode.LOSE_ARGUMENTS.getCode(),ResponseCode.LOSE_ARGUMENTS.getDesc());
            }
        }

        ResponseMessage responseResult = responseHelper.getResponseMessageTemplate().getResponseMessage();
        return  responseResult;
    }

    /**
     * @Description Update information of administrator.
     * @Author { fanglexue on 2019/11/7  at 11:10 AM }
     * @Path /admin/updateAdmin
    */
    @RequestMapping(value="/updateAdmin",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage updateAdmin(@RequestBody RequestMessage requestMessage){
        ResponseHelper responseHelper = new ResponseHelper();
        List<List<JmzAdminUser>> adminDtoSS = requestHelper.mapDataSet(objectMapper,requestMessage,
                JmzAdminUser.class);
        try {
            adminUserService.updateAdminUser(adminDtoSS);
            responseHelper.setResponseBCode(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc());
        }catch (BusinessException e){
            responseHelper.setResponseBCode(e.getCode(),e.getMessage());
        }
        ResponseMessage responseResult = responseHelper.getResponseMessageTemplate().getResponseMessage();
        return  responseResult;
    }

    /**
     * @Description Save information of administrator.
     * @Author { fanglexue  2019/11/7 }
     * @Path /admin/saveAdmin
     */
    @RequestMapping(value="/saveAdmin",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage saveAdmin(@RequestBody RequestMessage requestMessage){
        ResponseHelper responseHelper = new ResponseHelper();
        List<List<JmzAdminUser>> adminDtoSS = requestHelper.mapDataSet(objectMapper,requestMessage,
                JmzAdminUser.class);
        try {
            adminUserService.saveAdminUser(adminDtoSS);
            responseHelper.setResponseBCode(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc());
        }catch (BusinessException e){
            responseHelper.setResponseBCode(e.getCode(),e.getMessage());
        }
        ResponseMessage responseResult = responseHelper.getResponseMessageTemplate().getResponseMessage();
        return  responseResult;
    }


    /**
     * @Description Delete  administrator records.
     * @Author { Create by fanglexue on 2019/11/7 at 11:11 AM }
     * @Path  admin/deleteAdmin
     */
    @RequestMapping(value="/deleteAdmin",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage deleteAdmin(@RequestBody RequestMessage requestMessage){
        ResponseHelper responseHelper = new ResponseHelper();
        List<List<JmzAdminUser>> adminDtoSS = requestHelper.mapDataSet(objectMapper,requestMessage,
                JmzAdminUser.class);
        try {
            adminUserService.deleteAdminUser(adminDtoSS);
            responseHelper.setResponseBCode(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc());
        }catch (BusinessException e){
            responseHelper.setResponseBCode(e.getCode(),e.getMessage());
        }
        ResponseMessage responseResult = responseHelper.getResponseMessageTemplate().getResponseMessage();
        return  responseResult;
    }

    /**
     * @Description Find administrator more information.
     * @Author { Create by fanglexue on 2019/11/77 at3:07 PMM }
     * @Path admin/info
     **/
    @RequestMapping(value="/info",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getInfo(@RequestBody RequestMessage requestMessage){
        ResponseHelper responseHelper = new ResponseHelper();
        try {
            requestHelper.checkoutCondition(requestMessage,"getAdminInfo");
            RequestMessageTemplate requestMT = new RequestMessageTemplate(requestMessage);
            Condition cond = requestMT.getConditionByKey("adminId");
            Integer adminId = Integer.valueOf(cond.getValue());
            JmzAdminUser jmzAdminUser = adminUserService.getAdminInfo(adminId);
            List<JmzAdminUser>  lj = new ArrayList<>();
            lj.add(jmzAdminUser);
            //Entities are converted to DTOs
            ModelMapper modelMapper = new ModelMapper();
            List<AdminUserDto> userDTOS = modelMapper.map(lj,new TypeToken<List<AdminUserDto>>(){}.getType());
            responseHelper.setResponseDataSet("adminInfo",userDTOS);
            responseHelper.setResponseBCode(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc());
        }catch (BusinessException e){
            responseHelper.setResponseBCode(e.getCode(),e.getMessage());
        }
        ResponseMessage responseResult = responseHelper.getResponseMessageTemplate().getResponseMessage();
        return  responseResult;

    }


    /**
    @RequestMapping(value="/roleList",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getAdminRoles(@RequestBody RequestMessage requestMessage){
        RequestMessageTemplate requestMessageTemplate = new RequestMessageTemplate(requestMessage);
        List<com.jmz.apt.api.message.request.Data> dataSet = requestMessageTemplate.getDataSet();
        //JmzAdminRole jmzAdminRole = adminRoleDao.findOne(1);
        String res = stringRedisTemplate.opsForValue().get(AptConstant.Redis.ROLE_PREFIX + "1");
        //System.out.println(res);
        ArrayList<JmzAdminResource> resources = JsonSerializerUtil.string2Obj(res,ArrayList.class,JmzAdminResource.class);
        //System.out.println(JsonSerializerUtil.string2Obj(list.get(0),JmzAdminResource.class));
        //System.out.println(jmzAdminRole.getUsers());
        responseMessageTemplate.setBussResponse(ResponseCode.AUTHENTICATION_FAILURE.getCode(),"测试");
        ResponseMessage responseResult = responseMessageTemplate.getResponseMessage();
        return  responseResult;

    }
    **/

    /**
     * @Description : {  修改密码 }
     * @Author : create by NanFeng on 2019/11/6  12:35
     */
    @RequestMapping(value="/changePassword",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage changePassword(@RequestBody RequestMessage requestMessage){
        // 解析参数，获取user对象
        RequestMessageTemplate req = new RequestMessageTemplate(requestMessage);
        Map map = ObjectUtil.toObj(req.getDataSetByKey("user").get(0), Map.class);
        JmzAdminUser user = ObjectUtil.map2Object(map,JmzAdminUser.class);

        AdminTokenDto agent = SecurityContextHolder.getAgent();
        user.setId( agent.getAdminId());
        user.setPassword(MD5Util.encode(user.getPassword()));
        user.setUpdateTime(new Date());
        boolean flag = adminUserService.changePassword(user);

        if(flag)
            return responseMessageTemplate.setBussResponse(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDesc());
        else
            return responseMessageTemplate.setBussResponse(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
    }
}
